<style lang="less">
</style>
<template>
  <div class="search">
    <Row>
      <Col>
        <Card>
          <Row>
            <Form
              ref="searchForm"
              :model="searchForm"
              inline
              :label-width="90"
              @submit.native.prevent
              class="search-form"
            >
              <Form-item label="Vip名称" prop="vipName">
                <Input
                  type="text"
                  v-model="searchForm.vipName"
                  clearable
                  placeholder="请输入Vip名称"
                  style="width: 200px"
                />
              </Form-item>
              <Form-item style="margin-left:-35px;" class="br">
                <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                <Button @click="handleReset">重置</Button>
              </Form-item>
            </Form>
          </Row>
          <Row class="operation">
            <Button @click="add" v-has="'add'" type="primary" icon="md-add">添加Vip</Button>
          </Row>
          <!-- <Row>
          <Alert show-icon>
            已选择
            <span class="select-count">{{selectCount}}</span> 项
            <a class="select-clear"
               @click="clearSelectAll">清空</a>
          </Alert>
          </Row>-->
          <Row>
            <Table
              :loading="loading"
              max-height="600"
              border
              :columns="columns"
              :data="data"
              sortable="custom"
              @on-sort-change="changeSort"
              @on-selection-change="showSelect"
              ref="table"
            ></Table>
          </Row>
          <Row type="flex" justify="end" class="page">
            <Page
              :current="searchForm.current"
              :total="total"
              :page-size="searchForm.size"
              @on-change="changePage"
              @on-page-size-change="changePageSize"
              :page-size-opts="[10,20,50,100]"
              size="small"
              show-total
              show-elevator
              show-sizer
            ></Page>
          </Row>
        </Card>
      </Col>
    </Row>

    <Modal
      :title="modalTitle"
      v-model="vipModalVisible"
      :mask-closable="false"
      :width="520"
      :styles="{top: '100px'}"
    >
      <Form ref="vipForm" :model="vipForm" :label-width="110" :rules="rulesForm">
        <Form-item label="Vip模板名称" prop="vipName">
          <Input
            type="text"
            v-model="vipForm.vipName"
            clearable
            placeholder="请输入Vip模板名称"
            style="width: 350px"
          />
        </Form-item>
        <Form-item label="设备型号" prop="deviceModel">
          <Input
            type="text"
            v-model="vipForm.deviceModel"
            clearable
            placeholder="请输入设备型号"
            style="width: 350px"
          />
        </Form-item>
        <Form-item label="有效天数" prop="validDay">
          <Input
            type="text"
            v-model="vipForm.validDay"
            clearable
            placeholder="请输入有效天数"
            style="width: 350px"
          />
        </Form-item>
        <Form-item label="价格" prop="vipPrice">
          <Input
            type="text"
            v-model="vipForm.vipPrice"
            clearable
            placeholder="请输入价格"
            style="width: 350px"
          />
        </Form-item>
        <Form-item label="折扣" prop="discount">
          <Input
            type="text"
            v-model="vipForm.discount"
            :max="1"
            clearable
            placeholder="请输入折扣"
            style="width: 350px"
          />
        </Form-item>
        <Form-item label="是否有效" prop="isvalid">
          <i-Switch v-model="vipForm.isvalid" :true-value="1" :false-value="0">
            <span slot="open">有效</span>
            <span slot="close">无效</span>
          </i-Switch>
        </Form-item>
      </Form>
      <div slot="footer">
        <Button type="text" @click="vipModalVisible = false">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submit">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { getVipPageList, addVip, editVip, deleteVip } from "@/api/operate";
import { validateBool } from "@/libs/validate";
import departmentChoose from "../../my-components/xboot/department-choose";
import departmentTreeChoose from "../../my-components/xboot/department-tree-choose";
import circleLoading from "../../my-components/circle-loading.vue";

import util from "@/libs/util.js";

export default {
  name: "vip-manage",
  components: {
    circleLoading,
    departmentChoose,
    departmentTreeChoose
  },
  data() {
    return {
      switchVal: true,
      loading: true,
      operationLoading: false,
      loadingExport: true,
      vipModalVisible: false,
      drop: true,
      dropDownContent: "展开",
      dropDownIcon: "ios-arrow-down",
      selectCount: 0,
      selectList: [],
      dataDep: [],
      searchForm: {
        vipId: "",
        vipName: "",
        deviceModel: "",
        validDay: "",
        vipPrice: "",
        current: 1,
        size: 20
      },
      vipForm: {
        vipId: "",
        vipName: "",
        deviceModel: "",
        validDay: "",
        vipPrice: "",
        discount: "",
        isvalid: "",
        createBy: "",
        createDate: ""
      },
      rulesForm: {
        vipName: [
          { required: true, message: "VIP模板名称不能为空", trigger: "blur" }
        ],
        deviceModel: [
          {
            required: true,
            message: "设备型号不能为空",
            trigger: "blur"
          }
        ],
        validDay: [
          {
            required: true,
            message: "有效天数不能为空",
            trigger: "blur",
            type: "integer"
          }
        ],
        vipPrice: [
          {
            required: true,
            message: "价格不能为空",
            trigger: "blur",
            type: "integer"
          }
        ],
        discount: [
          {
            required: true,
            message: "折扣不能为空,小于0大于1",
            trigger: "blur",
            max: 1,
            min: 0,
            type: "number"
          }
        ]
      },
      selectDate: null,
      modalType: 0,
      modalTitle: "",
      submitLoading: false,
      columns: [
        {
          title: "序号",
          type: "index",
          width: 65,
          align: "center",
          fixed: "left"
        },
        {
          title: "Vip模板名称",
          key: "vipName",
          minWidth: 200,
          sortable: true,
          align: "center",
          fixed: "center"
        },
        {
          title: "设备型号",
          key: "deviceModel",
          width: 140,
          sortable: true,
          align: "center",
          fixed: "center"
        },
        {
          title: "有效天数",
          key: "validDay",
          minWidth: 120,
          align: "center",
          fixed: "center"
        },
        {
          title: "价格",
          key: "vipPrice",
          minWidth: 130,
          align: "center",
          fixed: "center"
        },
        {
          title: "折扣",
          key: "discount",
          align: "center",
          fixed: "center",
          minWidth: 150
        },

        {
          title: "状态",
          key: "isvalid",
          align: "center",
          width: 140,
          render: (h, params) => {
            if (params.row.isvalid == 1) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "有效"
                  }
                })
              ]);
            } else {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "error",
                    text: "无效"
                  }
                })
              ]);
            }
          },
          filters: [
            {
              label: "有效",
              value: "true"
            },
            {
              label: "无效",
              value: "false"
            }
          ],
          filterMultiple: false,
          filterMethod(value, row) {
            return value.toString() == row.status.toString();
          }
        },
        {
          title: "创建人",
          key: "createBy",
          align: "center",
          fixed: "center",
          sortable: true,
          sortType: "desc",
          width: 150
        },
        {
          title: "创建时间",
          key: "createTime",
          fixed: "center",
          align: "center",
          sortable: true,
          sortType: "desc",
          width: 150
        },
        {
          title: "操作",
          key: "action",
          width: 180,
          align: "center",
          fixed: "right",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  directives: [
                    {
                      name: "has",
                      value: "edit"
                    }
                  ],
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.row);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  directives: [
                    {
                      name: "has",
                      value: "delete"
                    }
                  ],
                  on: {
                    click: () => {
                      this.remove(params.row);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      data: [],
      total: 0
    };
  },
  methods: {
    init() {
      this.loadGetVipPageList();
    },
    handleSelectDepTree(v) {
      this.vipForm.departmentId = v[0];
    },
    handleSelectDep(v) {
      this.searchForm.departmentId = v;
    },
    changePage(v) {
      this.searchForm.current = v;
      this.loadGetVipPageList();
      this.clearSelectAll();
    },
    changePageSize(v) {
      this.searchForm.size = v;
      this.loadGetVipPageList();
    },
    loadGetVipPageList() {
      this.loading = true;
      getVipPageList(this.searchForm).then(res => {
        this.loading = false;
        if (res.code == 0) {
          // 将true和false转换为字符串的true和false
          this.data = res.data.records;
          this.total = res.data.total;
        }
      });
    },
    handleSearch() {
      this.searchForm.current = 1;
      this.searchForm.size = 20;
      this.loadGetVipPageList();
    },
    handleReset() {
      this.$refs.searchForm.resetFields();
      this.searchForm.current = 1;
      this.searchForm.size = 20;
      this.selectDate = null;
      this.searchForm.startDate = "";
      this.searchForm.endDate = "";
      this.selectDep = [];
      this.searchForm.departmentId = "";
      // 重新加载数据
      this.loadGetVipPageList();
    },
    changeSort(e) {
      this.searchForm.sort = e.key;
      this.searchForm.order = e.order;
      if (e.order == "normal") {
        this.searchForm.order = "";
      }
      this.loadGetVipPageList();
    },
    handleDropdown(name) {
      if (name == "refresh") {
        this.loadGetVipPageList();
      } else if (name == "reset") {
        if (this.selectCount <= 0) {
          this.$Message.warning("您还未选择要重置密码的用户");
          return;
        }
        this.$refs.checkPass.show();
      } else if (name == "exportData") {
        if (this.selectCount <= 0) {
          this.$Message.warning("您还未选择要导出的数据");
          return;
        }
        this.$Modal.confirm({
          title: "确认导出",
          content: "您确认要导出所选 " + this.selectCount + " 条数据?",
          onOk: () => {
            this.$refs.exportTable.exportCsv({
              filename: "用户数据"
            });
          }
        });
      } else if (name == "exportAll") {
        this.vipModalVisible = true;
      } else if (name == "importData") {
        this.$Modal.info({
          title: "请获取完整版",
          content: "支付链接: http://xpay.exrick.cn/pay?xboot"
        });
      }
    },
    exportAll() {
      getAllUserData().then(res => {
        this.vipModalVisible = false;
        if (res.success) {
          this.exportData = res.result;
          setTimeout(() => {
            this.$refs.exportTable.exportCsv({
              filename: "用户全部数据"
            });
          }, 1000);
        }
      });
    },

    add() {
      this.modalType = 0;
      this.modalTitle = "添加Vip";
      this.$refs.vipForm.resetFields();
      this.vipForm.isvalid = 1;
      this.vipModalVisible = true;
    },
    edit(v) {
      this.modalType = 1;
      this.modalTitle = "编辑Vip";
      this.$refs.vipForm.resetFields();
      // 转换null为""
      for (let attr in v) {
        if (v[attr] == null) {
          v[attr] = "";
        }
      }
      let str = JSON.stringify(v);
      let data = JSON.parse(str);
      this.vipForm = data;
      this.vipModalVisible = true;
    },
    remove(v) {
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除VIP模板 " + v.vipName + " ?",
        loading: true,
        onOk: () => {
          deleteVip(v.vipId).then(res => {
            this.$Modal.remove();
            if (res.code == 0) {
              this.$Message.success("删除成功");
              this.loadGetVipPageList();
            } else {
              this.$Message.error(res.msg);
            }
          });
        }
      });
    },
    dropDown() {
      if (this.drop) {
        this.dropDownContent = "展开";
        this.dropDownIcon = "ios-arrow-down";
      } else {
        this.dropDownContent = "收起";
        this.dropDownIcon = "ios-arrow-up";
      }
      this.drop = !this.drop;
    },
    showSelect(e) {
      this.exportData = e;
      this.selectList = e;
      this.selectCount = e.length;
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    delAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning("您还未选择要删除的数据");
        return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        ontent: "您确认要删除所选的 " + this.selectCount + " 条数据?",
        loading: true,
        onOk: () => {
          let ids = "";
          this.selectList.forEach(function(e) {
            ids += e.id + ",";
          });
          ids = ids.substring(0, ids.length - 1);
          deleteUser(ids).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("删除成功");
              this.clearSelectAll();
              this.loadGetVipPageList();
            }
          });
        }
      });
    },
    /**
     * 提交新增Vip
     * @param newForm
     */
    submit() {
      let _this = this;

      if (_this.modalType == 0) {
        _this.$refs.vipForm.validate(valid => {
          if (valid) {
            this.submitLoading = true;
            let obj = util.deepClone(_this.vipForm);
            console.log("submit", obj);
            addVip(_this.vipForm).then(
              res => {
                this.submitLoading = false;
                if (res.code == 0) {
                  this.$Message.success("新增成功");
                  _this.vipModalVisible = false;
                  _this.loadGetVipPageList();
                }
              },
              error => {
                console.log("submit error", JSON.stringify(error));
              }
            );
          }
        });
      } else {
        _this.$refs.vipForm.validate(valid => {
          if (valid) {
            this.submitLoading = true;
            let obj = util.deepClone(_this.vipForm);
            editVip(obj).then(
              res => {
                this.submitLoading = false;
                if (res.code == 0) {
                  this.$Message.success("编辑成功");
                  _this.vipModalVisible = false;
                  _this.loadGetVipPageList();
                }
              },
              error => {
                console.log("submit error", JSON.stringify(error));
              }
            );
          }
        });
      }
    }
  },
  mounted() {
    this.init();
  }
};
</script>
